<!DOCTYPE html>
<script src="../../resources/run-after-layout-and-paint.js"></script>
<svg>
  <linearGradient id="f">
    <stop stop-color="red"/>
  </linearGradient>
  <rect width="100" height="100" fill="url(#f) orange"/>
</svg>
<script>
runAfterLayoutAndPaint(function() {
  const svgNs = 'http://www.w3.org/2000/svg';
  let gradient = document.createElementNS(svgNs, 'linearGradient');
  let stop = gradient.appendChild(document.createElementNS(svgNs, 'stop'));
  stop.setAttribute('stop-color', 'green');
  gradient.id = 'f';

  let existingGradient = document.getElementById('f');
  document.querySelector('svg').insertBefore(gradient, existingGradient);
}, true);
</script>
